package com.woniu.atms.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.woniu.atms.entity.G5Order;
import com.woniu.atms.entity.G5Schedule;
import com.woniu.atms.entity.G5Ticket;
import com.woniu.atms.entity.G5TicketSite;
import com.woniu.atms.exception.ServiceException;
import com.woniu.atms.exception.pre.ticket.*;
import com.woniu.atms.mapper.G5OrderDao;
import com.woniu.atms.mapper.UserTicketDao;
import com.woniu.atms.service.UserTicketService;
import com.woniu.atms.vo.pre.ticket.PreTicketCheckedVO;
import com.woniu.atms.vo.pre.ticket.PreUserTicketVO;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @author 张奇
 * @title: UserTicketServiceImpl
 * @projectName g5_atms
 * @description:
 * @date 2022/1/19 16:02
 */
@Service
public class UserTicketServiceImpl implements UserTicketService {

    @Resource
    private UserTicketDao userTicketDao;

    @Resource
    private G5OrderDao g5OrderDao;


    @Override
    public PageInfo<PreUserTicketVO> queryAll(Integer pageNum, Integer pageSize) {
        //设置pageHelper属性
        PageHelper.startPage(pageNum, pageSize);
        List<PreUserTicketVO> list = userTicketDao.queryAll();
        return new PageInfo<>(list);
    }

    @Override
    public PageInfo<PreUserTicketVO> queryAllByUserId(Integer userId, Integer pageNum, Integer pageSize) {
        //设置pageHelper属性
        PageHelper.startPage(pageNum, pageSize);
        List<PreUserTicketVO> list = userTicketDao.queryAllByUserId(userId);
        return new PageInfo<>(list);
    }

    @Override
    @Transactional
    public boolean deleteById(Integer id) {
        //判断车票是否已经使用（已验票）,否者无法删除
        G5Ticket ticket = userTicketDao.queryById(id);
        //如果车票不存在
        if (ticket == null) {
            throw new TicketIsNullException("没有查询到该车票");
        }
        //如果车票未被退票且车票还未被使用
        if (!"y".equals(ticket.getReTicket())&&!"y".equals(ticket.getIsCheck())) {
            throw new TicketIsUnUseException("该车票还未被使用，无法删除");
        }
        //删除车票
        userTicketDao.deleteById(id);
        return true;
    }

    @Override
    public PageInfo<PreUserTicketVO> queryChecked(String checked, Integer userId, Integer pageNum, Integer pageSize) {
        //设置pageHelper属性
        PageHelper.startPage(pageNum, pageSize);
        List<PreUserTicketVO> list = userTicketDao.queryChecked(checked, userId);
        return new PageInfo<>(list);
    }

    @Override
    @Transactional
    public boolean reTicketByOrderId(Integer id) {
        G5Order order = g5OrderDao.queryById(id);
        //如果订单不是成功支付状态
        if (!"y".equals(order.getIsOk())) {
            return false;
        }
        //修改订单退票状态 退票时间
        order.setIsOk("n");
        g5OrderDao.update(order);
        List<G5Ticket> tickets= userTicketDao.queryByOrderId(id);
        tickets.forEach(e->{
            reTicket(e.getId());
        });
        return true;
    }

    @Override
    @Transactional
    public boolean reTicket(Integer id){
        G5Ticket ticket = userTicketDao.queryById(id);
        //如果该车票不存在或被删除或已验票或已退票则抛出异常
        //如果车票不存在
        if (ticket == null) {
            throw new TicketIsNullException("没有查询到该车票");
        }
        //如果车票已经被退票，则无法在退票
        if ("y".equals(ticket.getReTicket())) {
            throw new TicketIsReException("该车票已经被退票，无法再次退票");
        }
        //如果车票已经超过退票时间（发车前一小时不能退.

        //拿到现在时间，+一小时 后的时间
        Calendar rightNow = Calendar.getInstance();
        rightNow.add(Calendar.HOUR, 1);
        Date date = rightNow.getTime();
        //拿到车票规定的发车时间
        //查出车票日期
        G5TicketSite ticketSite = userTicketDao.queryTSByTSId(ticket.getTimeSeatId());
        //查出班次时刻
        G5Schedule schedule = userTicketDao.querySBySId(ticketSite.getScheduleId());
        //合并发车时间
        SimpleDateFormat s = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat s1 = new SimpleDateFormat("yyyy-MM-dd");
        //拿到日期字符串
        String dateStr = s1.format(ticketSite.getDate());
        //拿到时间字符串
        String timeStr = schedule.getTime().toString();
        //拿到发车date
        Date goDate = null;
        try {
            goDate = s.parse(dateStr + " " + timeStr);
        } catch (ParseException e) {
            e.printStackTrace();
            System.out.println("===退票接口 日期合并错误");
        }
        //如果现在时间+1小时 大于发车时间，说明超过退票时间，抛出异常
        if (date.getTime() > goDate.getTime()) {
            throw new TicketReOutTimeException("已经超过退票时间，无法退票");
        }


        //修改座位选择状为未选态
        userTicketDao.updateTimeSeatY(ticket.getTimeSeatId());
        //修改车票退票状态为y
        userTicketDao.updateReTicket(id);
        return true;
    }

    @Override
    public boolean checkedTicket(String no) {
        //查询车票是否存在
        G5Ticket ticket = userTicketDao.queryByNo(no);
        //如果车票不存在
        if (ticket == null) {
            throw new TicketIsNullException("没有查询到该车票");
        }
        //如果车票已经被退票，则无法在退票
        if ("y".equals(ticket.getReTicket())) {
            throw new TicketIsReException("该车票已经被退票，无法使用");
        }
        //如果车票已使用
        if ("y".equals(ticket.getIsCheck())) {
            throw new TicketIsUseException("该车票已经被使用，无法重复使用");
        }
        userTicketDao.updateCheckedY(ticket.getId());
        return true;
    }


}
